package com.tsvetanv.controller;

import java.io.File;
import java.io.FileOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

public class HandleUploadController extends AbstractController {
	private final static Logger logger = Logger
			.getLogger(HandleUploadController.class);
	private File destinationDir;

	public void setDestinationDir(File destinationDir) {
		this.destinationDir = destinationDir;
	}

	public void afterPropertiesSet() throws Exception {
		if (destinationDir == null) {
			throw new IllegalArgumentException("Must specify destinationDir");
		} else if (!destinationDir.isDirectory() && !destinationDir.mkdir()) {
			throw new IllegalArgumentException(destinationDir + " is not a "
					+ "directory, or it couldn't be created");
		}
	}

	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		response.setContentType("text/plain");

		if (!(request instanceof MultipartHttpServletRequest)) {
			response.sendError(HttpServletResponse.SC_BAD_REQUEST,
					"Expected multipart request.");
			logger.info("Is MultipartRequest: "
					+ (request instanceof MultipartHttpServletRequest));
			return null;
		}

		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile file = multipartRequest.getFile("uploaded");
		logger.info("destinationDir: "+destinationDir);
		File destination = File.createTempFile("file", "uploaded.txt",
				destinationDir);
		logger.info("AbsolutePath: " + destination.getAbsolutePath());
		FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(
				destination));

		response.getWriter().write("Success, wrote to " + destination);
		response.flushBuffer();
		return null;
	}
}
